package br.com.tiespec.web.ManagedBean;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.inject.Named;

import org.primefaces.context.RequestContext;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import br.com.tiespec.ejb.EjbInterface.AtorInterface;
import br.com.tiespec.model.Enum.TipoSortOrder;
import br.com.tiespec.model.Modelo.Ator;
import br.com.tiespec.model.Util.RNException;
import br.com.tiespec.web.Util.InitUtil;
import br.com.tiespec.web.Util.MsgUtil;
import br.com.tiespec.web.Util.WebUtil;

@Named("atorBean")
@SessionScoped
public class AtorBean implements Serializable {

	private static final long serialVersionUID = -4987790603498712639L;

	@EJB private AtorInterface ejb;
	
	private Ator atorInstance;
	private Ator atorInstanceTemp;
	private LazyDataModel<Ator> atorList;
	private Ator[] atorSelect;
	
	private Long idClientePortal;
	
	private String varBuscaAtor;
	private String msgExclusao;
	
	public String ator(){
		init();
		idClientePortal = WebUtil.getClientePortalEmContexto().getId();
		return "/views/atores/show.xhtml";
	}
	
	@PostConstruct
	public void init(){
		atorInstance = new Ator();
		atorInstanceTemp = new Ator();
		varBuscaAtor = "";
		atorList = InitUtil.inicializaAtorList();
		atorSelect = new Ator[0];
		filtrar();
	}
	
	public void goCreate(){
		atorInstance = new Ator();
	}
	
	public void salvar(){
		try {
			atorInstance.setCliente(WebUtil.getClientePortalEmContexto());
			ejb.salvarAtor(atorInstance);
			MsgUtil.msgSucesso("inc", atorInstance.getNome());
		} catch (RNException e){
			MsgUtil.msgErro("inc", atorInstance.getNome());
		}
		filtrar();
	}
	
	public void goEdit(Long id){
		atorInstance = ejb.selecionarAtor(id);
	}
	
	public void atualizar(){
		try {
			atorInstance.setCliente(WebUtil.getClientePortalEmContexto());
			ejb.atualizarAtor(atorInstance);
			MsgUtil.msgSucesso("alt", atorInstance.getNome());
		} catch (RNException e){
			MsgUtil.msgErro("alt", atorInstance.getNome());
		}
		filtrar();
	}
	
	public void goDelete(){
		RequestContext contexto = RequestContext.getCurrentInstance();
		Integer size = atorSelect.length;
		if (size == 0){
			contexto.execute("dialogoSelecione.show();");
			return;
		}
		if (size == 1){
			for (Ator ator: atorSelect){
				msgExclusao = MsgUtil.getMensagem("DialogoExcluir_MensagemUnico", ator.getNome());
			}
		} else {
			String msg = "";
			Integer count = 0;
			for (Ator ator:atorSelect){
				msg += "'" + ator.getNome() + "'";
				count++;
				if (count==(size-1))
					msg += " e ";
				else if (count != size)
					msg += ", ";
			}
			msgExclusao = MsgUtil.getMensagem("DialogoExcluir_MensagemMultiplo", msg);
		}
		contexto.execute("dialogoExcluir.show();");
	}
	
	public void excluir(){
		for (Ator ator:atorSelect) {
			try {
				ejb.removerAtor(ator.getId());
				MsgUtil.msgSucesso("exc", ator.getNome());
			} catch (RNException e){
				MsgUtil.msgErro("exc", ator.getNome());
			}
		}
		filtrar();
	}
	
	@SuppressWarnings("serial")
	public void filtrar(){
		atorList = new LazyDataModel<Ator>() {
			@Override
			public List<Ator> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
				WebUtil.setDataTableRows(pageSize);
				return ejb.listarAtor(first, pageSize, sortField, 
					TipoSortOrder.convertePrimeFaces(sortOrder.toString()), idClientePortal, varBuscaAtor);
			}
			@Override  
	        public Ator getRowData(String rowKey) {  
	        	try {
		            return ejb.selecionarAtor(Long.parseLong(rowKey));
	        	} catch (NumberFormatException e){
	        		return new Ator();
	        	}
	        }  
	        @Override  
	        public String getRowKey(Ator objeto)  
	        {  
	        	if (objeto!=null)
	        		return ""+objeto.getId();
	        	return "";
	        }  
		};
		atorList.setRowCount(ejb.countAtor(idClientePortal, varBuscaAtor));
		atorList.setPageSize(5);
	}
	
	@SuppressWarnings("serial")
	public void filtrarTodos(){
		atorList = new LazyDataModel<Ator>() {
			@Override
			public List<Ator> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
				WebUtil.setDataTableRows(pageSize);
				return ejb.listarAtor(first, pageSize, sortField, 
					TipoSortOrder.convertePrimeFaces(sortOrder.toString()), idClientePortal, null);
			}
			@Override  
	        public Ator getRowData(String rowKey) {  
	        	try {
		            return ejb.selecionarAtor(Long.parseLong(rowKey));
	        	} catch (NumberFormatException e){
	        		return new Ator();
	        	}
	        }  
	        @Override  
	        public String getRowKey(Ator objeto)  
	        {  
	        	if (objeto!=null)
	        		return ""+objeto.getId();
	        	return "";
	        }  
		};
		atorList.setRowCount(ejb.countAtor(idClientePortal, null));
		atorList.setPageSize(5);
	}
	
	public void validateNomeUnico(FacesContext context, UIComponent toValidate, Object value) {  
		String nome = (String) value;
	    if (nome == null || nome.trim().length() < 1){
	    	((UIInput)toValidate).setValid(false);
	    	FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,MsgUtil.getMensagem("Ator_Validate_NomeUnico", nome), "");
	    	context.addMessage(toValidate.getClientId(context), message); 
	    	return;
	    }
	    Boolean existeRegistro = ejb.validateNomeUnico(nome, idClientePortal, atorInstance.getId()); 
	    if (!existeRegistro){
	    	((UIInput)toValidate).setValid(false);
	    	FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,MsgUtil.getMensagem("Ator_Validate_NomeUnico", nome), "");
	    	context.addMessage(toValidate.getClientId(context), message); 
	    	return;
	    }
	}
	
	public String goHome(){
		this.destroy();
		return "goHome";
	}
	
	@PreDestroy
	public void destroy(){
		atorInstance = null;
		atorInstanceTemp = null;
		atorList = null;
		atorSelect = null;
		varBuscaAtor = null;
		msgExclusao = null;
	}

	public Ator getAtorInstance() {
		return atorInstance;
	}

	public void setAtorInstance(Ator atorInstance) {
		this.atorInstance = atorInstance;
	}

	public Ator getAtorInstanceTemp() {
		return atorInstanceTemp;
	}

	public void setAtorInstanceTemp(Ator atorInstanceTemp) {
		this.atorInstanceTemp = atorInstanceTemp;
	}

	public LazyDataModel<Ator> getAtorList() {
		return atorList;
	}

	public void setAtorList(LazyDataModel<Ator> atorList) {
		this.atorList = atorList;
	}

	public String getVarBuscaAtor() {
		return varBuscaAtor;
	}

	public void setVarBuscaAtor(String varBuscaAtor) {
		this.varBuscaAtor = varBuscaAtor;
	}
	
	public Ator[] getAtorSelect() {
		return atorSelect;
	}
	
	public void setAtorSelect(Ator[] atorSelect) {
		this.atorSelect = atorSelect;
	}
	
	public String getMsgExclusao() {
		return msgExclusao;
	}
	
	public void setMsgExclusao(String msgExclusao) {
		this.msgExclusao = msgExclusao;
	}
}